package com.jyh.order.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.jyh.order.bean.Order;
import com.jyh.order.feign.ProductFeignClient;
import com.jyh.order.service.OrderService;
import com.jyh.product.bean.Product;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {

    private final DiscoveryClient discoveryClient; // 服务发现
    private final RestTemplate restTemplate; // restTemplate
    private final LoadBalancerClient loadBalancerClient; // 负载均衡
    private final ProductFeignClient productFeignClient;


    @SentinelResource(value = "createOrder",blockHandler = "createOrderFallback")
    @Override
    public Order createOrder(Long productId, Long userId) {
        // Product product = getProductFromRemoteWithLoadBalancerAnnotation(productId);

        // 使用feign完成远程调用
        Product product = productFeignClient.getProductById(productId);
        Order order = new Order();
        order.setId(1L);
        // 总金额
        order.setTotalAmount(product.getPrice().multiply(BigDecimal.valueOf(product.getNum())));
        order.setUserId(userId);
        order.setNickName("jyh");
        order.setAddress("北京");
        // 远程查询商品列表
        order.setProductList(Arrays.asList(product));
        return order;
    }

    //兜底回调
    public Order createOrderFallback(Long productId, Long userId, BlockException e){
        Order order = new Order();
        order.setId(0L);
        order.setTotalAmount(new BigDecimal("0"));
        order.setUserId(userId);
        order.setNickName("未知用户");
        order.setAddress("异常信息："+e.getClass());

        return order;
    }

    // 发送请求
    private Product getProductFromRemote(Long productId) {
        // 1. 获取到商品服务所在的所有机器IP + port
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        ServiceInstance instance = instances.get(0);
        // 2. 根据IP + port调用商品服务
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + productId;
        log.info("调用商品服务: {}", url);
        // 调用商品服务
        return restTemplate.getForObject(url, Product.class);
    }

    // 进阶2：完成负载均衡发送请求
    private Product getProductFromRemoteWithLoadBalancer(Long productId) {
        // 1. 获取到商品服务所在的所有机器IP + port
        ServiceInstance choose = loadBalancerClient.choose("service-product");
        // 2. 根据IP + port调用商品服务
        String url = "http://" + choose.getHost() + ":" + choose.getPort() + "/product/" + productId;
        log.info("调用商品服务: {}", url);
        // 调用商品服务
        return restTemplate.getForObject(url, Product.class);
    }

    // 进阶3：基于注解的负载均衡
    private Product getProductFromRemoteWithLoadBalancerAnnotation(Long productId) {
        String url = "http://service-product/product/" + productId;
        // 调用商品服务，service-product为服务名称, 会被动态替换
        return restTemplate.getForObject(url, Product.class);
    }
}